from django.shortcuts import render, HttpResponse, redirect
from django import forms
from io import BytesIO

from app01 import models
from app01.utils.bootstrap import BootStrapForm
from app01.utils.encrypt import md5
from app01.utils.code import check_code


class LoginForm(BootStrapForm):
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput,
        required=True
    )
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput(render_value=True),
        required=True
    )
    code = forms.CharField(
        label="验证码",
        widget=forms.TextInput,
        required=True
    )

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        return md5(pwd)


def login(request):
    """ 登录 """
    if request.method == "GET":
        form = LoginForm()
        return render(request, 'login.html', {"form": form})
    form = LoginForm(data=request.POST)
    # print(form)
    if form.is_valid():

        # 1.校验图形验证码
        # form.cleaned_data={'username':xx,'password':xx,}
        # 之前从页面获取到用户输入的code 和 暂时存在session的正确的图面验证码
        # 下一步数据库校验，里面是没有'code'的，所以不用get而用pop
        user_input_code = form.cleaned_data.pop('code')
        code = request.session.get('image_code', "")

        ############## 待解决：局域网 平板出不来验证码 暂时-关闭验证 ##################

        # if code.upper() != user_input_code.upper():
        #     form.add_error("code", "验证码错误！")
        #     return render(request, 'login.html', {"form": form})

        # 2.校验数据库中的用户名和密码
        # form.cleaned_data={'username':xx,'password':xx,}数据库校验,获取用户对象，无-None，
        # admin_object=models.Admin.objects.filter(username=form.cleaned_data["username"],password=form.cleaned_data.get("password"),)
        admin_object = models.Admin.objects.filter(**form.cleaned_data).first()
        if not admin_object:
            # 未通过验证，展示错误信息 "用户名或密码错误"写在”password“位置下面
            form.add_error("password", "用户名或密码错误")
            return render(request, 'login.html', {"form": form})
        # 用户名，密码正确
        request.session['info']={"id":admin_object.id,"name":admin_object.username}
        request.session.set_expiry(60*60*24*7) # 7天免登陆
        # 网站生成一个随机字符串；写到浏览器的cookie中，再写入到session中的info{}中
        request.session['info'] = {'id': admin_object.id, 'username': admin_object.username}

        return redirect('/admin/list/')
    return render(request, 'login.html', {"form": form})


def image_code(request):
    """ 生成图片验证码 """
    img, code_string = check_code()
    # print(code_str)

    # session保存,以便用来校验验证码
    request.session['image_code'] = code_string
    # 设置60s超时刷新验证码,过了60秒就读取不到了
    request.session.set_expiry(60)

    # 暂存到内存中
    stream = BytesIO()
    img.save(stream, 'png')
    # img.show()
    return HttpResponse(stream.getvalue())


def logout(request):
    """ 注销 """
    request.session.clear()

    return redirect('/login/')
